package servlet;

import model.DBUtil;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: 杰
 * @date: 2024/1/18 17:54
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.读取参数中的用户名和密码
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("您的用户名或密码为空！");
        }
        //2.从数据库中读取账户和密码进行验证
        UserDao userDao = new UserDao();
        User user = userDao.getUserByUserName(username);
        if (user == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户不存在");
            return;
        }
        if (user.getPassword().equals(password)) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误");
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        //跳转到主页
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法，来反馈当前用户的登录状态
        HttpSession httpSession = req.getSession(false);
        if (httpSession == null) {
            resp.setStatus(403);
            return;
        }
        User user = (User) httpSession.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
        }
    }
}
